import React, { useState, useCallback } from 'react';
import type { ViewConfig } from '../../../types/room';
import styles from '../styles/TimeAxisSelector.module.css';

// 时间视图配置
export const TIME_VIEW_CONFIGS: Record<string, ViewConfig> = {
  hour: {
    type: 'hour' as const,
    title: '小时视图',
    dateRange: 48, // 48小时
    cellWidth: 80,
    timeFormat: 'HH:mm',
    description: '2天48小时，适合当日排房和短期调度',
  },
  day: {
    type: 'day' as const,
    title: '日视图',
    dateRange: 30, // 30天
    cellWidth: 60,
    timeFormat: 'MM/DD',
    description: '30天视图，适合月度房态管理',
  },
  week: {
    type: 'week' as const,
    title: '周视图',
    dateRange: 84, // 12周
    cellWidth: 50,
    timeFormat: 'ww周',
    description: '12周视图，适合季度规划',
  },
  month: {
    type: 'month' as const,
    title: '月视图',
    dateRange: 365, // 12个月
    cellWidth: 40,
    timeFormat: 'MM月',
    description: '年度视图，适合长期分析和预测',
  },
};

// 快速时间范围预设
export const QUICK_RANGES = [
  { label: '今天', days: 1, icon: '📅' },
  { label: '本周', days: 7, icon: '📆' },
  { label: '本月', days: 30, icon: '🗓️' },
  { label: '本季度', days: 90, icon: '📊' },
  { label: '半年', days: 180, icon: '📈' },
  { label: '全年', days: 365, icon: '🎯' },
];

interface TimeAxisSelectorProps {
  currentView: string;
  currentRange: number;
  startDate: Date;
  onViewChange: (viewType: string, config: ViewConfig) => void;
  onRangeChange: (startDate: Date, endDate: Date, days: number) => void;
  onQuickRange: (days: number) => void;
}

const TimeAxisSelector: React.FC<TimeAxisSelectorProps> = ({
  currentView,
  currentRange,
  startDate,
  onViewChange,
  onRangeChange,
  onQuickRange,
}) => {
  const [isRangePickerOpen, setIsRangePickerOpen] = useState(false);
  const [customStartDate, setCustomStartDate] = useState(
    startDate.toISOString().split('T')[0]
  );
  const [customEndDate, setCustomEndDate] = useState(() => {
    const end = new Date(startDate);
    end.setDate(end.getDate() + currentRange);
    return end.toISOString().split('T')[0];
  });

  // 处理视图切换
  const handleViewChange = useCallback(
    (viewType: string) => {
      const config = TIME_VIEW_CONFIGS[viewType];
      if (config) {
        onViewChange(viewType, config);
      }
    },
    [onViewChange]
  );

  // 处理快速范围选择
  const handleQuickRange = useCallback(
    (days: number) => {
      onQuickRange(days);
    },
    [onQuickRange]
  );

  // 处理自定义日期范围
  const handleCustomRange = useCallback(() => {
    const start = new Date(customStartDate);
    const end = new Date(customEndDate);

    if (start <= end) {
      const days = Math.ceil(
        (end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24)
      );
      onRangeChange(start, end, days);
      setIsRangePickerOpen(false);
    }
  }, [customStartDate, customEndDate, onRangeChange]);

  // 时间导航
  const navigateTime = useCallback(
    (direction: 'prev' | 'next') => {
      const config = TIME_VIEW_CONFIGS[currentView];
      const multiplier = direction === 'next' ? 1 : -1;

      let offset: number;
      switch (config.type) {
        case 'hour':
          offset = 24 * multiplier; // 前进/后退24小时
          break;
        case 'day':
          offset = 7 * multiplier; // 前进/后退7天
          break;
        case 'week':
          offset = 28 * multiplier; // 前进/后退4周
          break;
        case 'month':
          offset = 90 * multiplier; // 前进/后退3个月
          break;
        default:
          offset = currentRange * multiplier;
      }

      const newStartDate = new Date(startDate);
      if (config.type === 'hour') {
        newStartDate.setHours(newStartDate.getHours() + offset);
      } else {
        newStartDate.setDate(newStartDate.getDate() + offset);
      }

      const newEndDate = new Date(newStartDate);
      if (config.type === 'hour') {
        newEndDate.setHours(newEndDate.getHours() + config.dateRange);
      } else {
        newEndDate.setDate(newEndDate.getDate() + config.dateRange);
      }

      onRangeChange(newStartDate, newEndDate, config.dateRange);
    },
    [currentView, currentRange, startDate, onRangeChange]
  );

  // 回到今天
  const goToToday = useCallback(() => {
    const today = new Date();
    const config = TIME_VIEW_CONFIGS[currentView];
    const endDate = new Date(today);

    if (config.type === 'hour') {
      endDate.setHours(endDate.getHours() + config.dateRange);
    } else {
      endDate.setDate(endDate.getDate() + config.dateRange);
    }

    onRangeChange(today, endDate, config.dateRange);
  }, [currentView, onRangeChange]);

  // 获取当前日期范围显示文本
  const getCurrentRangeText = useCallback(() => {
    const config = TIME_VIEW_CONFIGS[currentView];
    const end = new Date(startDate);

    if (config.type === 'hour') {
      end.setHours(end.getHours() + config.dateRange);
      return `${startDate.toLocaleDateString()} ${startDate.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })} - ${end.toLocaleDateString()} ${end.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`;
    } else {
      end.setDate(end.getDate() + config.dateRange);
      return `${startDate.toLocaleDateString()} - ${end.toLocaleDateString()}`;
    }
  }, [currentView, startDate]);

  return (
    <div className={styles.timeAxisSelector}>
      {/* 视图切换器 */}
      <div className={styles.viewSwitcher}>
        <span className={styles.sectionLabel}>视图模式：</span>
        <div className={styles.viewButtons}>
          {Object.entries(TIME_VIEW_CONFIGS).map(([key, config]) => (
            <button
              key={key}
              className={`${styles.viewButton} ${currentView === key ? styles.active : ''}`}
              onClick={() => handleViewChange(key)}
              title={config.description}
            >
              {config.title}
            </button>
          ))}
        </div>
      </div>

      {/* 时间导航器 */}
      <div className={styles.timeNavigator}>
        <button
          className={styles.navButton}
          onClick={() => navigateTime('prev')}
          title='前一时段'
        >
          ⬅️
        </button>

        <div className={styles.currentRange}>
          <span className={styles.rangeText}>{getCurrentRangeText()}</span>
          <span className={styles.rangeInfo}>
            ({TIME_VIEW_CONFIGS[currentView].description})
          </span>
        </div>

        <button
          className={styles.navButton}
          onClick={() => navigateTime('next')}
          title='后一时段'
        >
          ➡️
        </button>

        <button
          className={styles.todayButton}
          onClick={goToToday}
          title='回到今天'
        >
          📍 今天
        </button>
      </div>

      {/* 快速范围选择 */}
      <div className={styles.quickRanges}>
        <span className={styles.sectionLabel}>快速选择：</span>
        <div className={styles.quickButtons}>
          {QUICK_RANGES.map((range, index) => (
            <button
              key={index}
              className={`${styles.quickButton} ${currentRange === range.days ? styles.active : ''}`}
              onClick={() => handleQuickRange(range.days)}
              title={`显示${range.days}天`}
            >
              {range.icon} {range.label}
            </button>
          ))}

          <button
            className={styles.customButton}
            onClick={() => setIsRangePickerOpen(!isRangePickerOpen)}
            title='自定义时间范围'
          >
            🎛️ 自定义
          </button>
        </div>
      </div>

      {/* 自定义日期范围选择器 */}
      {isRangePickerOpen && (
        <div className={styles.customRangePicker}>
          <div className={styles.customRangeHeader}>
            <span>📅 自定义时间范围</span>
            <button
              className={styles.closeButton}
              onClick={() => setIsRangePickerOpen(false)}
            >
              ❌
            </button>
          </div>

          <div className={styles.dateInputs}>
            <div className={styles.dateInput}>
              <label>开始日期：</label>
              <input
                type='date'
                value={customStartDate}
                onChange={e => setCustomStartDate(e.target.value)}
              />
            </div>

            <div className={styles.dateInput}>
              <label>结束日期：</label>
              <input
                type='date'
                value={customEndDate}
                onChange={e => setCustomEndDate(e.target.value)}
              />
            </div>
          </div>

          <div className={styles.customRangeActions}>
            <button className={styles.applyButton} onClick={handleCustomRange}>
              ✅ 应用
            </button>
            <button
              className={styles.cancelButton}
              onClick={() => setIsRangePickerOpen(false)}
            >
              ❌ 取消
            </button>
          </div>
        </div>
      )}

      {/* 视图信息提示 */}
      <div className={styles.viewInfo}>
        <span className={styles.infoText}>
          💡 当前：{TIME_VIEW_CONFIGS[currentView].title} | 范围：{currentRange}
          天 | 单元格宽度：{TIME_VIEW_CONFIGS[currentView].cellWidth}px
        </span>
      </div>
    </div>
  );
};

export default TimeAxisSelector;
